﻿/*
 * Please leave this Copyright notice in your code if you use it
 * Written by Decebal Mihailescu [http://www.codeproject.com/script/articles/list_articles.asp?userid=634640]
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CommonUtils
{
    using System.Reflection;
    using System.Text.RegularExpressions;
    using System.ComponentModel.Composition;
    using System.ComponentModel.Composition.Hosting;
    using System.ComponentModel;
    using System.Globalization;
    using Microsoft.Win32;
    using System.Diagnostics;
    using System.IO;

    using MyTextImport = Lazy<ITextImport, ITextImportMetaData>;
    public interface ITextImportMetaData
    {
        [System.ComponentModel.DefaultValue(false)]
        bool SpecialFormat { get; }
        string Description { get; }
        string FileExtension { get; }
        [System.ComponentModel.DefaultValue("")]
        string Provider { get; }
        [System.ComponentModel.DefaultValue(false)]
        bool HasLicense { get; }
        [System.ComponentModel.DefaultValue("")]
        string ContextMenuText { get; }
        [System.ComponentModel.DefaultValue("")]
        string IconName { get; }
        [System.ComponentModel.DefaultValue("")]
        string URL { get; }
    }


    public interface ITextImport
    {
        // Methods
        string GetAllTextFromFile(string fileName, out Encoding encoding);
        event EventHandler ProgressChanged;
    }



    public class MEFController
    {
        private MEFController() { }
        static readonly MEFController _inst = new MEFController();
        static private MEFController Instance
        {
            get { return _inst; }
        }
        #region MEF
        private CompositionContainer _container;

        void CreateMEFParts()
        {
            // System.Windows.Forms.MessageBox.Show("entered CreateMEFParts()");
            if (_container != null)
                return;

            //An aggregate catalog that combines multiple catalogs
            var catalog = new AggregateCatalog();
            //Adds all the parts found in the same assembly as the Program class
            // System.Windows.Forms.MessageBox.Show("entry assembly in CreateMEFParts()= " + Assembly.GetEntryAssembly().Location);
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetAssembly(typeof(CommonUtils.MEFController))));
            catalog.Catalogs.Add(new DirectoryCatalog(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)));
            Trace.TraceInformation("In CREATE MEF Parts the path is  {0}", System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
/*
#if(DEBUG)
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetAssembly(typeof(CommonUtils.MEFController))));
            catalog.Catalogs.Add(new DirectoryCatalog(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)));
            Trace.TraceInformation("In CREATE MEF Parts the path is  {0}", System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
#else
            string[] folders = PersistedSharedData.PlugInDirectories.ToArray();
            if (folders.Count() == 0)
                catalog.Catalogs.Add(new DirectoryCatalog(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)));
            else
                foreach (string folder in folders)
                {
                    catalog.Catalogs.Add(new DirectoryCatalog(folder));
                }
#endif
 */
            //Create the CompositionContainer with the parts in the catalog
            _container = new CompositionContainer(catalog);

            //Fill the imports of this object

            try
            {
                this._container.ComposeParts(this);
            }
            catch (CompositionException compositionException)
            {
                Trace.TraceError("Composition Exception in '{0}'  because {1}", compositionException.StackTrace, compositionException.Message);
                _container.Dispose();
                _container = null;
            }
            catch (System.Reflection.ReflectionTypeLoadException Ex)
            {
                Trace.TraceError("ReflectionTypeLoadException in '{0}'  because {1}", Ex.StackTrace, Ex.Message);
                _container.Dispose();
                _container = null;
            }
            catch (Exception ex)
            {
                Trace.TraceError("Exception in '{0}'  because {1}", ex.StackTrace, ex.Message);
                _container.Dispose();
                _container = null;
            }
        }

#pragma warning disable 649
        [Import("TextExtractor", typeof(ITextImportController))]
        Lazy<ITextImportController, Dictionary<string, object>> _PlugInImportController;// { get; set; }
#pragma warning restore 649
        public static ITextImportController PlugInImportController
        {
            get
            {
                // System.Windows.Forms.MessageBox.Show("in get_PlugInController");
                if (Instance._container == null)
                    Instance.CreateMEFParts();
                //if (Instance._PlugInController.Value == null)
                //System.Windows.Forms.MessageBox.Show("_PlugInController.Value is null" + Instance._strWebSite);
                if (Instance._PlugInImportController == null)
                {
                    Trace.TraceWarning("_PlugInImportController is null");
                    return null;
                }
                else
                {
                    if(Instance._PlugInImportController.Value == null)
                        Trace.TraceWarning("_PlugInImportController.Value is null");
                }
                return Instance._PlugInImportController.Value;
            }
        }
        #endregion
    }

}
